﻿using System;
using System.Collections.Generic;
using FairyGUI;
using UnityEngine;
public class FEditCardPanel : MyWindow
{
    FSelectListMediator _selectImgPanel;
    GTextField _imgText;
    GTextField _idText;
    GTextInput _nameEditBox;
    FCard _realCard;

    Controller _selectProCtrl;
    Controller _levelControl;

    GList _selectPropertyBtnList;
    GList _selectPropertyList;
    GList _showPropertyList;
    GList _roleTypeList;

    GComboBox _typeDownList;
    GComboBox _skillDownList;
    GComboBox _demageDownList;

    List<SkillBase> _levelSkillList;
    List<PropertyValue<object>> _hasPropertyList;

    Card _cardData;
    Card _preCardData;
    int _cardIndex;

    public FEditCardPanel()
    {
        this.contentPane = UIPackage.CreateObject("CardPackage", "EditCardPanel").asCom;
        //组件获取
        _imgText = this.contentPane.GetChild("imgText").asTextField;
        _realCard = (FCard)this.contentPane.GetChild("realCard");
        _idText = this.contentPane.GetChild("idText").asTextField;
        _nameEditBox = this.contentPane.GetChild("nameEditBox").asTextInput;
        _showPropertyList = this.contentPane.GetChild("showPropertyList").asList;
        _selectPropertyList = this.contentPane.GetChild("selectPropertyList").asList;
        _selectPropertyBtnList = this.contentPane.GetChild("selectPropertyBtnList").asList;
        _roleTypeList = this.contentPane.GetChild("roleTypeList").asList;
        _typeDownList = this.contentPane.GetChild("typeDownList").asComboBox;
        _skillDownList = this.contentPane.GetChild("skillDownList").asComboBox;
        _demageDownList = this.contentPane.GetChild("demageDownList").asComboBox;
        _levelControl = this.contentPane.GetController("LevelControl");
        _selectProCtrl = this.contentPane.GetController("SelectProCtrl");

        //按钮事件监听
        this.contentPane.GetChild("exitBtn").onClick.Add(OnExitPanel);
        this.contentPane.GetChild("saveBtn").onClick.Add(OnSaveBtnClick);
        this.contentPane.GetChild("delBtn").onClick.Add(OnDelBtnClick);
        this.contentPane.GetChild("selectImgBtn").onClick.Add(OnSelectImgBtn);
        //控制器
        _levelControl.onChanged.Add(OnLevelCtrlChange);
        _selectProCtrl.onChanged.Add(OnSelectProCtrlChange);
        //下拉框
        _typeDownList.onChanged.Add(OnTypeDownListChange);
        _skillDownList.onChanged.Add(OnSkillDownListChange);
        _demageDownList.onChanged.Add(OnDemageDownListChange);
        //文本
        _nameEditBox.onFocusOut.Add(OnNameEditBoxOut);
        //列表
        _showPropertyList.itemRenderer = RenderListItem;
        _selectPropertyBtnList.itemRenderer = RenderBtnListItem;
        _selectPropertyList.itemRenderer = RenderSelectPropertyListItem;
        _selectPropertyList.onClickItem.Add(OnSelectPropertyListClick);
        _roleTypeList.onClickItem.Add(OnRoleTypeChange);
    }

    protected override void OnInit()
    {
        base.OnInit();
        this.Center();
    }
    /// <summary>
    /// 编写其他需要在窗口显示时处理的业务逻辑。
    /// </summary>
    protected override void OnShown()
    {
        base.OnShown();
 
    }
    /// <summary>
    /// 定时器
    /// </summary>
    protected override void OnUpdate()
    {
        base.OnUpdate();
        _realCard.Fresh(_levelControl.selectedIndex);
    }
    public void InitData(Card card,int cardIndex)
    {
        CheckDataChange(() => {
            ResetPanel();
            _preCardData = card;
            _cardData = card.DeepClone();
            _cardIndex = cardIndex;

            _idText.text = _cardData.id;
            _realCard.InitData(_cardData,false);
            _imgText.text = _cardData.img;
            _nameEditBox.text = _cardData.GetCardName();
            _typeDownList.selectedIndex = (int)_cardData.type;
            _demageDownList.selectedIndex = (int)_cardData.elementType;
            _skillDownList.selectedIndex = (int)_cardData.skillType;
            for(int i = 0;i < _cardData.roles.Count;i++){
                _roleTypeList.GetChildAt((int)_cardData.roles[i]).asButton.selected = true;
            }
            FresSelecthPropertyPanel();
            FreshCardBackground();
        });
    }
    private void ResetPanel(){
        _roleTypeList.SelectNone();
    }
    /// <summary>
    /// 刷新属性操作面板
    /// </summary>
    private void FresSelecthPropertyPanel()
    {
        //清除数据
        _selectProCtrl.ClearPages();
        _selectPropertyBtnList.RemoveChildrenToPool();
        _showPropertyList.RemoveChildrenToPool();
        //赋给全局变量，方便使用
        _levelSkillList = _cardData.skill;

        var levelSkill = GetLevelSkill();
        for (int i = 0; i < levelSkill.propertyList.Count; i++)
        {
            _selectProCtrl.AddPage("page_" + i);
        }
        //1级 如果本来就是0，则手动调用变化
        if(_levelControl.selectedIndex == 0) OnLevelCtrlChange(null);
        _levelControl.selectedIndex = 0;
        //在控制器页面生成完后再渲染
        _selectPropertyBtnList.numItems = levelSkill.propertyList.Count;
        //需要选项
        _selectProCtrl.selectedIndex = 0;
    }
    /// <summary>
    /// 刷新卡牌背景图
    /// </summary>
    private void FreshCardBackground(){
        
    }
    /// <summary>
    /// 已选择的属性列表
    /// </summary>
    /// <param name="index"></param>
    /// <param name="item"></param>
    void RenderListItem(int index, GObject item)
    {
        //如果为空则重新拿值
        if(_hasPropertyList == null) GetHasPropertyList();
        var _item = item.asCom;
        _item.GetChild("showPropertybtn").onClick.Add(OnShowPropertyListModifyClick);
        _item.GetChild("closePropertyBtn").onClick.Add(OnShowPropertyListCloseClick);
        _item.GetChild("showPropertybtn").asButton.title = _hasPropertyList[index].GetDiscript();
    }
    /// <summary>
    /// 选择属性分类按钮列表
    /// </summary>
    /// <param name="index"></param>
    /// <param name="item"></param>
    void RenderBtnListItem(int index, GObject item)
    {
        var levelSkill = GetLevelSkill();
        item.asCom.GetChild("title").asTextField.text = levelSkill.propertyList[index].GetDiscript(false); 
    }
    /// <summary>
    /// 供选择的属性列表
    /// </summary>
    /// <param name="index"></param>
    /// <param name="item"></param>
    void RenderSelectPropertyListItem(int index, GObject item)
    {
        var property = GetLevelProperty();
        var propertyList = property.val.propertyList;
        item.asCom.GetChild("title").asTextField.text = propertyList[index].GetDiscript(false);
    }
    /// <summary>
    /// 编写其他需要在窗口隐藏时处理的业务逻辑。
    /// </summary>
    protected override void OnHide()
    {
        base.OnHide();
        if (_selectImgPanel != null && _selectImgPanel.isShowing) _selectImgPanel.Hide();
    }
    private void OnExitPanel()
    {
        CheckDataChange(() => {
            _cardData.ActiveRandProperty();
            _preCardData = null;
            this.Hide();
        });
    }
    private void CheckDataChange(ZeroDeletegate cb){
        if(_preCardData == null) {
            cb();
            return;
        }
        var isEqual = Utils.CompareObject(_preCardData,_cardData);
        var isChange = this.TextIsChange(false);
        //判断是否有改变
        if(!isEqual || isChange){
            FUIMain.TipPanel("卡牌数据发生改变，确定放弃本次修改？", (status) => {
                if ((int)status == 1)
                {
                    cb();
                }
            });
        }else{
            cb();
        }
    }
    /// <summary>
    /// 判断文字是否发生改变
    /// </summary>
    /// <returns></returns>
    private bool TextIsChange(bool isSave = true){
        var isChange = false;
        //判断是否需要重新保存名字
        if(_preCardData.GetCardName() != _nameEditBox.text)
        {
            if(isSave) LTLocalization.AddText(_preCardData.name, _nameEditBox.text);
            isChange = true;
        }
        return isChange;
    }
    private void OnSelectImgBtn()
    {
        _selectImgPanel = (FSelectListMediator)FUIMain.ShowPanel(GMConfig.PanelType.SelecImgtPanel);
        _selectImgPanel.InitData("CardImgPackage",PackageItemType.Image,OnSelectImgCB);
    }
    private void OnSelectImgCB(object imgUrl)
    {
        _imgText.text = imgUrl.ToString();
        _cardData.img = imgUrl.ToString();
        _realCard.Fresh();
    }
    /// <summary>
    /// 刷新已有属性显示面板
    /// </summary>
    /// <param name="count"></param>
    private void FreshShowPropertyList(int count)
    {
        _showPropertyList.RemoveChildrenToPool();
        _showPropertyList.numItems = count;
    }
    /// <summary>
    /// 等级控制器
    /// </summary>
    /// <param name="context"></param>
    private void OnLevelCtrlChange(EventContext context)
    {
        if (_levelControl.selectedIndex < 0) return;
        Debug.Log("OnLevelCtrlChange" + _levelControl.selectedIndex);
        //更新已有属性
        FreshShowPropertyList(GetHasPropertyList().Count);
    }
    /// <summary>
    /// 属性分类变化控制器
    /// </summary>
    /// <param name="context"></param>
    private void OnSelectProCtrlChange(EventContext context)
    {
        var _ctrl = (Controller)context.sender;
        if (_ctrl.selectedIndex < 0) return;
 
        Debug.Log("OnSelectProCtrlChange" + _ctrl.selectedIndex);
        _selectPropertyList.RemoveChildrenToPool();
        var property = GetLevelProperty();
        var propertyList = property.val.propertyList;
        _selectPropertyList.numItems = propertyList.Count;
    }
    /// <summary>
    /// 选择某一个属性
    /// </summary>
    /// <param name="context"></param>
    private void OnSelectPropertyListClick(EventContext context)
    {
        var index = _selectPropertyList.GetChildIndex((GObject)context.data);
        var property = GetLevelProperty();

        var descript = property.val.propertyList[index].GetDiscript(false);
        int num = Utils.GetCharNums(descript, @"\?");
        string str = "";
        for(int i = 0;i < num - 1; i++)
        {
            str += "-";
        }
        //不需要输入的
        if(num == 0)
        {
            property.val.propertyList[index].val = 1;
            FreshShowPropertyList(GetHasPropertyList().Count);
            Debug.Log("index:" + index + "count:" + _showPropertyList.numItems);
        }
        else
        {
            //如果已经有值，则修改
            if (property.val.propertyList[index].val.ToString() != "0") str = property.val.propertyList[index].val.ToString();
            FUIMain.InputPanel(str,(status,val) => {
                if((int)status == 1)
                {
                    property.val.propertyList[index].val = val;
                    FreshShowPropertyList(GetHasPropertyList().Count);
                }
            });
        }
    }
    /// <summary>
    /// 选择删除已有的某一个属性
    /// </summary>
    /// <param name="context"></param>
    private void OnShowPropertyListCloseClick(EventContext context)
    {
        var index = _showPropertyList.GetChildIndex(((GObject)context.sender).parent);
        _hasPropertyList[index].val = 0;
        _hasPropertyList.RemoveAt(index);
        FreshShowPropertyList(_hasPropertyList.Count);
        Debug.Log("close index:" + index + "count:" + _showPropertyList.numItems);
    }
    /// <summary>
    /// 选择修改已有的某一个属性
    /// </summary>
    /// <param name="context"></param>
    private void OnShowPropertyListModifyClick(EventContext context)
    {
        var index = _showPropertyList.GetChildIndex(((GObject)context.sender).parent);
        var descript = _hasPropertyList[index].GetDiscript(false);
        int num = Utils.GetCharNums(descript, @"\?");
        //没有?就不需要修改
        if (num == 0) return;
        FUIMain.InputPanel(_hasPropertyList[index].val.ToString(), (status,val) => {
            if((int)status == 1)
            {
                _hasPropertyList[index].val = val;
                FreshShowPropertyList(_hasPropertyList.Count);
            }
        });
        Debug.Log("modify index:" + index + "count:" + _showPropertyList.numItems);
    }
    /// <summary>
    /// 卡牌类型变化
    /// </summary>
    private void OnTypeDownListChange()
    {
        var cardType = (GMConfig.CardType)Enum.Parse(typeof(GMConfig.CardType),_typeDownList.value);
        _cardData.type = cardType;
        FreshCardBackground();
        Debug.Log(cardType);
    }
    /// <summary>
    /// 技能类型变化
    /// </summary>
    private void OnSkillDownListChange()
    {
        FUIMain.TipPanel("重新选择技能类型将会清除之前卡牌所有技能设置，是否要重新设置？", (status) => {
            if ((int)status == 1)
            {
                var skillType = (GMConfig.CardSkillType)Enum.Parse(typeof(GMConfig.CardSkillType), _skillDownList.value);
                _cardData.skillType = skillType;
                Debug.Log(skillType);
                FresSelecthPropertyPanel();
            }
            else
            {
                Debug.Log("重置" + (int)_cardData.skillType);
                _skillDownList.selectedIndex = (int)_cardData.skillType;
            }
        });
    }
    /// <summary>
    /// 伤害类型
    /// </summary>
    private void OnDemageDownListChange()
    {
        var demageType = (GMConfig.ElementType)Enum.Parse(typeof(GMConfig.ElementType),_demageDownList.value);
        _cardData.elementType = demageType;
    }
    /// <summary>
    /// 名字变化
    /// </summary>
    private void OnNameEditBoxOut()
    {
        Debug.Log(_nameEditBox.text);
        Debug.Log(_cardData.name);
    }
    /// <summary>
    /// 适用角色类型变化
    /// </summary>
    /// <param name="context"></param>
    private void OnRoleTypeChange(EventContext context)
    {
        var index = _roleTypeList.GetChildIndex((GObject)context.data);
        var roleType = (GMConfig.CardRoleType)Enum.Parse(typeof(GMConfig.CardRoleType), index.ToString());
        _cardData.RolesChange(roleType);
        Debug.Log("type" + roleType + "count" + _cardData.roles.Count);
    }
    /// <summary>
    /// 保存卡牌数据
    /// </summary>
    private void OnSaveBtnClick()
    {
        //判断是否需要重新保存名字
        var isChange = this.TextIsChange();
        if(isChange) LTLocalization.SaveDataToCSV();
        _preCardData = _cardData.DeepClone();
        var isOk = FCardListMediator.SaveCard(_preCardData,_cardIndex);
        var str = "保存成功！";
        if(!isOk) str = "保存失败！";
        FUIMain.TipPanel(str);
    }
    /// <summary>
    /// 保存卡牌数据
    /// </summary>
    private void OnDelBtnClick()
    {
        FUIMain.TipPanel("确定要删除本张卡牌？", (status) => {
            if ((int)status == 1)
            {
                FCardListMediator.DelCard(_cardIndex);
                _preCardData = null;
                this.Hide();
            }
        });
    }
    /// <summary>
    /// 获得具体等级的属性列表
    /// </summary>
    /// <returns></returns>
    private SkillBase GetLevelSkill()
    {
        return (SkillBase)_levelSkillList[_levelControl.selectedIndex];
    }
    /// <summary>
    /// 获得分类中的具体属性
    /// </summary>
    /// <returns></returns>
    private PropertyValue<PropertyBase> GetLevelProperty()
    {
        var levelSkill = GetLevelSkill();
        var property = (PropertyValue<PropertyBase>)levelSkill.propertyList[_selectProCtrl.selectedIndex];
        return property;
    }
    private List<PropertyValue<object>> GetHasPropertyList()
    {
        _hasPropertyList = _cardData.GetHasPropertyList(_levelControl.selectedIndex);
        return _hasPropertyList;
    }
    /// <summary>
    /// 获得所有可选类型
    /// </summary>
    /// <returns></returns>
    public Dictionary<string,List<string>> GetTypeDict()
    {
        var dict = new Dictionary<string, List<string>>();
        //卡牌类型
        var _typeTextList = GetChildrenText(_typeDownList,true);
        dict.AddOrReplace("typeTextList", _typeTextList);
        //技能类型
        var _skillTextList = GetChildrenText(_skillDownList,true);
        dict.AddOrReplace("skillTextList", _skillTextList);
        //角色类型
        var _roleTextList = GetChildrenText(_roleTypeList);
        dict.AddOrReplace("roleTextList", _roleTextList);

        return dict;
    }
    /// <summary>
    /// 获得指定控件子物体的text
    /// </summary>
    /// <param name="gComponent"></param>
    /// <returns></returns>
    private List<string> GetChildrenText(GComponent gComponent,bool isCombox = false)
    {
        var textList = new List<string>();
        if (isCombox)
        {
            var _gComponent = (GComboBox)gComponent;
            for (int i = 0; i < _gComponent.items.Length; i++)
            {
                textList.Add(_gComponent.items[i]);
            }
        }
        else
        {
            for (int i = 0;i < gComponent.numChildren; i++)
            {
                textList.Add(gComponent.GetChildAt(i).text);
            }
        }
        return textList;
    }
}

